<template>
  <div style="margin-bottom: 10px">
    <el-button size="small" @click="showDialog()">设置规则</el-button>
    <el-dialog
      top="10px"
      width="60%"
      title="设置规则"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <div>
        <div class="pos-contaienr">
          <p class="bg-title">新建规则</p>
          <el-input
            type="textarea"
            rows="5"
            v-model="requirement"
            placeholder="请输入要求"
          ></el-input>
          <el-button class="save-btn" size="small" type="primary" @click="saveRequirement()"
            >保 存</el-button
          >
        </div>

        <p class="bg-title">规则列表</p>
        <el-table :data="list" class="table-container" size="small" border style="width: 100%">
          <el-table-column prop="req" label="规则"> </el-table-column>
          <el-table-column prop="updated_at" label="时间"> </el-table-column>
          <el-table-column prop="submitter_username" label="提交人"> </el-table-column>
          <el-table-column prop="selected" label="选中状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.selected"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeInfo(scope.row.id, scope.row.selected)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="selected" label="操作">
            <template slot-scope="scope">
              <el-button size="small" @click="deleteInfo(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" class="confirm-btn" @click="dialogVisible = false"
            >关 闭</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getData, postData } from '@/service/getData';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import axios from 'axios';
export default {
  name: 'Doc',
  data() {
    return {
      chat_id: null,
      requirement: '',
      html: '',
      input_text: '',
      list: [],
      dialogVisible: false,
      isRequesting: false, // 是否正在请求
      abortController: null, // 用于取消请求的 AbortController
      messages: [
        {
          text: '暂无数据',
        },
      ],
      uploadParams: {
        uploadUrl: '/agent/corrector/upload_original_file',
        data: {},
        headers: {
          Authorization: '',
        },
        name: 'file',
        fileLists: [],
      },
    };
  },
  mounted() {
    let token = localStorage.getItem('token');
    this.uploadParams.headers['Authorization'] = 'Token ' + token;
    // this.getRequirement();
    this.getList();
  },
  methods: {
    deleteInfo(id) {
      axios
        .delete(
          `/agent/corrector/req/${id}/`,

          {
            headers: {
              authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.$message.success('删除成功');
          this.getList();
        })
        .finally(() => {
          this.getList();
        });
    },
    changeInfo(id, selected) {
      postData(
        `/agent/corrector/req/${id}/`,
        {
          selected: selected,
        },
        'post',
      )
        .then((res) => {
          // 将数组反转
          this.getList();
        })
        .finally(() => {
          this.getList();
        });
    },
    showDialog() {
      this.dialogVisible = true;
    },
    getList() {
      //
      getData('agent/corrector/req/', {}, 'get').then((res) => {
        // 将数组反转
        this.list = res;
      });
    },
    getRequirement() {
      getData('agent/test_point/requirement/', {}, 'get').then((res) => {
        // 将数组反转
        this.requirement = res.requirement;
      });
    },
    saveRequirement() {
      postData(
        'agent/corrector/req/',
        {
          req: this.requirement,
        },
        'post',
      )
        .then((res) => {
          // 将数组反转
          this.getList();
          this.requirement = '';
          this.$message.success('规则创建成功');
        })
        .catch((e) => {})
        .finally((v) => {});
    },
    testFn(val) {
      // 截取字符串中 ```markdown``` 之后的全部
      let newVal = val.substring(val.indexOf('```markdown') + 11);
      //
      // 将'```markdown' 之前的内容
      let preVal = val.substring(0, val.indexOf('```markdown'));
      newVal = newVal.slice(0, -3);

      // 判断字符串是否包含 ```markdown```
      if (val.indexOf('```markdown') !== -1) {
        // 包含 ```markdown```，进行处理
        newVal = val.substring(val.indexOf('```markdown') + 11);
      }
      if (val.indexOf('```') !== -1) {
        // 包含 ```markdown```，进行处理
        newVal = newVal.slice(0, -3);
      }
      console.log('要处理的markdown内容', newVal);
      return preVal + marked(newVal);
    },
    handleChatSubmit2(id, str, type) {
      let _this = this;
      if (_this.isRequesting) return;
      _this.isRequesting = true;

      if (_this.abortController) {
        _this.abortController.abort();
      }
      _this.abortController = new AbortController();
      // 创建新控制器并存储
      _this.$emit('saveMessage', {
        input_text: '思考中，请稍候...',
        type: 'add',
      });
      fetchEventSource(str, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          Authorization: this.uploadParams.headers['Authorization'],
          Accept: ['text/event-stream', 'application/json'],
        },
        body: JSON.stringify({
          question: id,
          chat_id: this.chat_id,
        }),
        openWhenHidden: true,
        signal: _this.abortController.signal, //与其相关联的signal属性
        onopen(e) {
          console.log(e, 'SSE在连接打开时被调用');
          if (e.status == 200) {
            _this.messages[_this.messages.length - 1].text = '<h2 class="think">';
            // _this.messages[_this.messages.length - 1].text = '思考中，请稍候...';
            // _this.messages[_this.messages.length - 1].text = '<h2 class="think">';
          } else {
            _this.messages[_this.messages.length - 1].text = '服务开小差了，请稍后重试';
            _this.$nextTick(() => {
              let chatBox = _this.$refs.chatBox;
              chatBox.scrollTop = chatBox.scrollHeight;
            });
          }
        },
        onmessage(msg, event) {
          // console.log('收到消息:', msg, event);
          if (msg.id) {
            _this.messages[_this.messages.length - 1].id = msg.id;
          }
          if (msg.event === 'answer') {
            const res = msg.data;
            if (res === '</think>') {
              _this.messages[_this.messages.length - 1].text += '</h2>';
            } else {
              _this.messages[_this.messages.length - 1].text += res;
            }

            _this.html = _this.testFn(_this.messages[_this.messages.length - 1].text);
            _this.$emit('saveMessage', {
              input_text: _this.html,
              type: 'replace',
            });
          } else if (msg.event === 'error') {
            // let obj = JSON.parse(res);
            const res = msg.data;
            _this.messages[_this.messages.length - 1].text = res;
          } else if (msg.event === 'chat_id') {
            _this.chat_id = msg.data;
          } else if (msg.event === 'id') {
            _this.uploadHistoryList();
          }
        },
        onclose(e) {
          _this.isRequesting = false;
          _this.abortController.abort();
          _this.$forceUpdate();
        },
        onerror(err) {
          _this.isRequesting = false;
          _this.abortController.abort();
          _this.$forceUpdate();
        },
      });
    },
    add() {
      if (!this.input_text) {
        this.$message.error('请输入问题');
        return;
      }
      this.messages[0].text = '暂无数据';
      this.html = '';
      this.$emit('saveMessage', {
        input_text: this.input_text,
        type: 'add',
      });
      this.handleChatSubmit2(this.input_text, 'agent/test_point/test_point_qa_sse/', '');
    },
  },
};
</script>
<style lang="scss" scoped>
.return-text {
  background: #fff;
  padding: 10px;
  color: #666;
  font-size: 14px;
}
.bg-title {
  background: #9fafcc;
  padding: 2px 10px;
  color: #fff;
  margin: 10px 0;
  font-size: 14px;
}
.pos-contaienr {
  position: relative;
  .save-btn {
    position: absolute;
    right: 10px;
    bottom: 10px;
  }
}
</style>
